<template>
  <div class="page-box">
    <div class="search-box">
      <el-form ref="form" class="botLeft  flex-wrap" :model="form" label-width="110px">
        <el-form-item class="elFormItem" label="订单号">
          <el-input maxlength="100" placeholder="请输入" v-model.trim="form.orderCode"></el-input>
        </el-form-item>
        <el-form-item class="elFormItem" label="手机号">
          <el-input maxlength="100" placeholder="请输入" v-model.trim="form.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item class="elFormItem" label="用户备注">
          <el-input maxlength="100" placeholder="请输入" v-model.trim="form.remark"></el-input>
        </el-form-item>
        <el-form-item class="elFormItem" label="开具类型">
          <el-select style="width:100%" v-model="form.headerType" placeholder="请选择">
            <el-option key="0" label="个人/非企业单位" value="0"></el-option>
            <el-option key="1" label="企业单位" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="elFormItem" label="状态">
          <el-select style="width:100%" v-model="form.status" placeholder="请选择">
            <el-option key="-1" label="申请失败" value="-1"></el-option>
            <el-option key="0" label="已申请" value="0"></el-option>
            <el-option key="1" label="开票中" value="1"></el-option>
            <el-option key="2" label="开票成功" value="2"></el-option>
            <el-option key="3" label="已发货" value="3"></el-option>
            <el-option key="4" label="已发货" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="elFormItem" style="width:auto;" label="">
          <el-button @click="getTableData()" icon="el-icon-search" type="primary">搜索</el-button>
          <el-button @click="clearList()">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="order-con-box">
      <div v-if="sumPage" class="operation-box cenBet">
        <div class="operation-left cenLeft">
          <el-button @click="createElectronicInvoice()">生成发票</el-button>
          <el-button @click="sendEmailElectronicInvoice()">重新发送</el-button>
        </div>
        <div class="operation-right">
          <el-button @click="leadOut()" icon="el-icon-download">导出</el-button>
        </div>
      </div>
      <el-table @selection-change="handleSelectionChange" v-loading="sreachLoding" element-loading-text="拼命加载中" ref="multipleTable" empty-text="暂无数据信息~" :data="table" border style="width: 100%">
        <el-table-column align="center" type="selection" width="60">
        </el-table-column>
        <el-table-column align="center" prop="orderCode" label="订单号"></el-table-column>
        <el-table-column width="100" align="center" label="发票状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==4">已退款</el-tag>
            <el-tag type="success" v-if="scope.row.status==3">已发货</el-tag>
            <el-tag v-if="scope.row.status==2">开票成功</el-tag>
            <el-tag v-if="scope.row.status==1">开票中</el-tag>
            <el-tag type="warning" v-if="scope.row.status==0">已申请</el-tag>
            <el-tag type="danger" v-if="scope.row.status==-1">申请失败</el-tag>
            <el-tag v-if="scope.row.status==-2">未申请</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="申请时间">
          <template slot-scope="scope" align="center">
            <p style=" text-align: center;" class="cellPLeft">
              {{$moment(scope.row.gmtCreate,"YYYY-MM-DD HH:mm" )}}
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发货时间">
          <template slot-scope="scope" align="center">
            <p v-if="scope.row.gmtModified" style=" text-align: center;" class="cellPLeft">
              {{$moment(scope.row.gmtModified,"YYYY-MM-DD HH:mm" )}}
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="totalPrice" label="发票金额">
          <template slot-scope="scope" align="center">
            <p style=" text-align: center;" class="cellPLeft">
              {{scope.row.totalPrice}}元
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发票类型">
          <template slot-scope="scope" align="center">
            <p style=" text-align: center;" class="cellPLeft">
              {{scope.row.submitType==0?'电子发票(增值税普通发票)':'纸质发票(增值税专用发票)'}}
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开具类型">
          <template slot-scope="scope" align="center">
            <p class="cellPLeft">
              {{scope.row.headerType==1?'企业单位':'个人/非企业单位'}}
            </p>
            <p v-if="scope.row.headerType==1" class="cellPLeft">
              <span>企业名称:{{scope.row.headerName}}</span>
              <span>企业税号:{{scope.row.taxNum}}</span>
            </p>
            <p v-else class="cellPLeft">
              <span>个人</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remark" label="用户备注"></el-table-column>
        <el-table-column align="center" prop="email" label="接收邮箱"></el-table-column>
        <el-table-column align="center" width="136" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button v-if="scope.row.status!=3" @click="editInvoice= JSON.parse(JSON.stringify(scope.row));editInvoiceAlert=true" type="text" size="mini">编辑</el-button>
            <el-button @click="qureyInvoiceById(scope.row)" type="text" size="mini">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="sumPage" class="pagination-box">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="thisPage" :page-sizes="$pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="sumPage">
      </el-pagination>
    </div>
    <!-- 编辑发票 -->
    <el-dialog title="编辑发票" width="860px" :visible.sync="editInvoiceAlert">
      <el-form style="width:810px;padding-left:25px; flex-wrap: wrap;" class="cenBet" :model="editInvoice">
        <el-form-item style="width:47%" label="开具类型">
          <el-select style="width:100%" v-model="editInvoice.headerType" placeholder="请选择">
            <el-option label="个人/非企业单位" :value="0" key="0"></el-option>
            <el-option label="企业单位" :value="1" key="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width:47%" label="发票抬头">
          <el-input v-if="editInvoice.headerType==1" maxlength="100" placeholder="请输入企业名称" v-model.trim="editInvoice.headerName"></el-input>
          <el-input v-else disabled="" maxlength="100" value="个人"></el-input>
        </el-form-item>
        <el-form-item style="width:47%" v-if="editInvoice.headerType==1" label="企业税号">
          <el-input maxlength="100" placeholder="请输入企业税号" v-model.trim="editInvoice.taxNum"></el-input>
        </el-form-item>
        <el-form-item style="width:47%" label="接收邮箱">
          <el-input maxlength="100" placeholder="请输入接收邮箱" v-model.trim="editInvoice.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editInvoiceAlert = false">取消</el-button>
        <el-button @click="sureEditInvoice()" type="primary">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="发票详情" width="860px" :visible.sync="phoneInvoiceAlert">
      <img :src="phoneInvoice">
      <div slot="footer" class="dialog-footer">
        <el-button @click="phoneInvoiceAlert=false" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pickerOptions from "@/components/js/pickerOptions.js";
import servicePub from "@/api/servicePub";
// import demoJson from "./demo";
import elementUIFun from "@/components/js/elementUIFun.js";
export default {
  data() {
    return {
      phoneInvoice: "", //发票照片
      phoneInvoiceAlert: false, //发票详情弹框
      editInvoice: {}, //发票数据
      editInvoiceAlert: false, //编辑发票
      sumPage: 0, //一共有多少条
      thisPage: 1, //当前页
      pageSize: 10, //每页多少条
      sreachLoding: false, //搜索loding
      table: [],
      form: {
        //搜索表单
        orderCode: "", //订单号
        phoneNumber: "", //用户手机号
        headerType: "", //发票抬头
        // gmtCreate: [], //申请时间
        remark: "", //用户备注
        status: "" //状态
      },
      pickerOptions: pickerOptions,
      saveSelect: [], //保存选择结果
      multipleSelection: [] // 选择结果
    };
  },
  computed: {
    thisActivityId() {
      return this.$store.state.activityId.thisActivityId;
    }
  },
  watch: {
    thisActivityId(a, b) {
      this.initFun();
    }
  },
  created() {
    this.initFun();
  },
  methods: {
    async initFun() {
      this.getTableData();
    },
    // 查询数据
    async getTableData() {
      delete this.form.gmtCreate;
      this.sreachLoding = true;
      let subData = {
        activityId: this.$store.state.activityId.thisActivityId,
        start: (this.thisPage - 1) * this.pageSize,
        size: this.pageSize,
        submitType: 0, //   提交发票类型 0电子 1纸质
        ...this.form
      };
      // console.log(subData);
      const { data = [] } = await servicePub.queryInvoiceByPagination(subData);
      this.sreachLoding = false;
      // console.log(data);
      this.table = data.data || [];
      this.sumPage = data.total || 0;
      // this.table = demoJson.result.data || [];
      // this.sumPage = demoJson.result.total;
    },
    // 查询发票详情
    async qureyInvoiceById(scopeRow) {
      const { data } = await servicePub.qureyInvoiceById({
        id: scopeRow.id,
        activityId: this.$store.state.activityId.thisActivityId
      });
      console.log(data);
      this.phoneInvoice = data.invoiceUrl;
      if (this.phoneInvoice) {
        this.phoneInvoiceAlert = true;
      } else {
        this.$message({
          message: "未获取到数据信息",
          type: "warning"
        });
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.thisPage = val;
      this.getTableData();
    },
    clearList() {
      this.form = {
        //搜索表单
        orderCode: "", //订单号
        phoneNumber: "", //用户手机号
        headerType: "", //发票抬头
        // gmtCreate: [], //申请时间
        remark: "", //用户备注
        status: "" //状态
      };
      this.getTableData();
    },
    // 生成发票
    async createElectronicInvoice() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请至少选择一项！",
          type: "warning"
        });
        return;
      }
      let ids = [];
      this.multipleSelection.map(item => {
        ids.push(item.id);
      });
      const confirm = await elementUIFun.$confirm(
        `此操作将进行生成发票, 是否继续?`
      );
      if (!confirm) {
        return;
      }
      let successNum = 0;
      for (let index = 0; index < ids.length; index++) {
        const element = ids[index];
        const { success = false } = await servicePub.createElectronicInvoice({
          activityId: this.$store.state.activityId.thisActivityId,
          ids: [element]
        });
        if (success) {
          successNum++;
        }
      }
      if (!successNum) {
        return;
      } else if (successNum < ids.length) {
        this.$message({
          message: "部分生成成功",
          type: "warning"
        });
      } else {
        this.$message({
          message: "生成成功！",
          type: "success"
        });
      }
      this.getTableData();
    },
    // 确定编辑发票信息
    async sureEditInvoice() {
      const editInvoice = {
        ...this.editInvoice
      };
      if (editInvoice.headerType == 1 && !editInvoice.headerName) {
        this.$message({
          message: "请输入企业名称",
          type: "warning"
        });
        return;
      }
      if (editInvoice.headerType == 1 && !editInvoice.taxNum) {
        this.$message({
          message: "请输入企业税号",
          type: "warning"
        });
        return;
      }
      if (!editInvoice.email) {
        this.$message({
          message: "请输入接收邮箱",
          type: "warning"
        });
        return;
      }
      let subData = {
        id: editInvoice.id,
        activityId: this.$store.state.activityId.thisActivityId
      };
      subData.headerType = editInvoice.headerType; //抬头类型
      subData.taxNum = editInvoice.taxNum; //税号
      subData.email = editInvoice.email; //接收邮箱
      if (editInvoice.headerType == 0) {
        subData.headerName = "个人"; //抬头名称
        subData.taxNum = "";
      } else {
        subData.headerName = editInvoice.headerName; //抬头名称
      }

      console.log(subData);
      const { success = false } = await servicePub.updateInvoiceById(subData);
      if (success) {
        this.editInvoiceAlert = false;
        this.$message({
          message: "更改成功",
          type: "success"
        });
        this.getTableData();
      }
    },
    // 重新发送
    async sendEmailElectronicInvoice() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请至少选择一项！",
          type: "warning"
        });
        return;
      }
      let ids = [];
      this.multipleSelection.map(item => {
        ids.push(item.id);
      });
      const confirm = await elementUIFun.$confirm(
        `此操作将进行重新发送, 是否继续?`
      );
      if (!confirm) {
        return;
      }

      let successNum = 0;
      for (let index = 0; index < ids.length; index++) {
        const element = ids[index];
        const { success = false } = await servicePub.sendEmailElectronicInvoice(
          {
            activityId: this.$store.state.activityId.thisActivityId,
            ids: [element]
          }
        );
        if (success) {
          successNum++;
        }
      }
      if (!successNum) {
        return;
      } else if (successNum < ids.length) {
        this.$message({
          message: "部分生成成功",
          type: "warning"
        });
      } else {
        this.$message({
          message: "生成成功！",
          type: "success"
        });
      }
      this.getTableData();
    },
    // 导出
    leadOut() {
      this.sreachLoding = true;
      this.$http
        .post(
          "/api/isv/invoice/exportInvoice",
          {
            // orderCode: "",
            // consignee: "",
            // phoneNumber: "",
            // headerType: "",
            // remark: "",
            // // gmtCreate: [],
            // status: "",
            activityId: this.$store.state.activityId.thisActivityId,
            submitType: 0
          },
          {
            responseType: "blob"
          }
        )
        .then(
          res => {
            console.log(res.data);
            this.sreachLoding = false;
            if (res.data.success === false) {
              this.$message({
                message: res.data.errorMsg || "导出失败",
                type: "warning"
              });
              return;
            }
            // const filename = decodeURI(
            //   res.headers["content-disposition"].split(";")[1].split("=")[1]
            // );
            // console.log(filename);
            let url = window.URL.createObjectURL(new Blob([res.data]));
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", "发票.xlsx");
            document.body.appendChild(link);
            link.click();
            this.$message({
              message: "导出成功",
              type: "success"
            });
          },
          err => {
            this.sreachLoding = false;
            this.$message.error("服务器出小差了");
          }
        );
    },
    // handleSelectionChange(val) {
    //   this.saveSelect = this.multipleSelection;
    //   this.multipleSelection = [];
    //   let isClear = false;
    //   for (let i = 0; i < val.length; i++) {
    //     if (val[i].status == "0") {
    //       this.multipleSelection.push(val[i]);
    //     } else {
    //       isClear = true;
    //     }
    //   }
    //   if (isClear) {
    //     this.toggleSelection();
    //   }
    // },
    // toggleSelection() {
    //   this.$refs.multipleTable.clearSelection();
    //   this.saveSelect.forEach(row => {
    //     this.$refs.multipleTable.toggleRowSelection(row);
    //   });
    // }
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>
<style scoped>
@import url("./invice.css");
</style>
